var fs = require('fs');
var dbConn = require("../controller/dbConn");
var db = dbConn.db;

var studentModel = require('../model/studentModel').StudentModel;
var personModel = require('../model/personModel').PersonModel;

var albums = function(callback) {

    fs.readdir('./uploadimg', function(err, files) {
        var allAlbums = [];
        (function iterator(i) {
            if (i == files.length) {
                callback(allAlbums);
                return;
            }
            fs.stat('./uploadimg/' + files[i], function(err, stats) {
                if (err) return console.error(err);
                if (stats.isDirectory()) {
                    allAlbums.push(files[i]);
                }
                iterator(i + 1);
            });

        })(0);
    });

};

var textCon = {
    firstPage: function(req, res, next) {
        albums(function(allAlbums) {
            res.render('myFirstPage', {
                albums: allAlbums
            });
        });

    },

    secPage: function(req, res, next) {
        var numb = Math.floor(Math.random() * 100 + 10);
        var personPost = {
            title: 'haha',
            name: 'String',
            parentId: numb,
        };
        personModel.create(personPost, function(err, doc) {
            if (err) {
                console.log(err);
                next(err);
            }
        });
        //ObjectId("58a563e087939a286893eae3")
        var post = {
            name: '我就随便写个借口玩玩',
            age: numb,
        };
        studentModel.create(post, function(err, doc) {
            if (err) {
                console.log(err);
                next(err);
            }
            res.json({ meta: { status: 1, message: "发布成功" }, data: doc });
            //res.end();
        });

    },

    thirPage: function(req, res, next) {
        studentModel.findOneAndUpdate({ _id: '58a4230023948311f6f8eeba' }, { person: '58a563e087939a286893eae3' }, function(err, doc) {
            if (err) return;
            res.json({ meta: { status: 1, message: "修成功" }, data: doc });
        });
    },
    fourPage: function(req, res, next) {
        studentModel
            .findById('58a4230023948311f6f8eeba')
            .populate({
                path: 'person',
                model: 'Person'
            })
            .exec(function(err, doc) {
                if (err) return;
                if (!doc) return;
                res.json({ meta: { status: 1, message: "获取成功" }, data: { truck: doc } });

            });
    },
};

module.exports = textCon;
